<?php

namespace App\Api\Controllers\Admin;

use App\Api\Requests\AdminPermissionRequest;
use App\Models\AdminPermission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class AdminPermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword');
        $status  = $request->get('status') ?? '10';
        $limit   = $request->get('limit') ?? 20;
        $page    = $request->get('page') ?? 1;
        $datas   = AdminPermission::query()
            ->when($keyword, function ($query, $keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orwhere('slug', 'like', "%{$keyword}%");
            })
            ->orderBy('sort', 'asc')
            ->paginate($limit, '*', '', $page);

        return $this->success([
            'list'      => $datas,
            'status'    => $status,
        ]);
    }

    /**
     * @param AdminPermissionRequest $request
     * @return mixed
     */
    public function store(AdminPermissionRequest $request)
    {
        $request->validated();
        $row = new AdminPermission($request->all());
        $row->save();

        return $this->success($request->all(), '数据创建成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * @param AdminPermissionRequest $request
     * @param $id
     * @return mixed
     */
    public function update(AdminPermissionRequest $request, $id)
    {
        $row = AdminPermission::find($id);
        $request->validated();
        $row->update($request->all());

        return $this->success($row->toArray(), '数据更新成功');
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        if (empty($id)) {
            return $this->error('请求处理失败，参数错误。');
        }

        $idArr  = explode(',', $id);
        $result = AdminPermission::destroy($idArr);

        return $this->success([$idArr], "成功处理 {$result} 条数据。");
    }
}
